package com.ruoyi.zsyh.controller.applet.after.factory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 服务订单 -- 厂家
 */
@Controller
@RequestMapping("/applet/zsyh/afterFactory")
public class ZsyhAfterFactoryAppletController extends BaseController
{

    @Autowired
    private IZsyhAfterFactoryService zsyhAfterFactoryService;

    @Autowired
    private IZsyhAfterFactoryLoginService zsyhAfterFactoryLoginService;

    @Autowired
    private IZsyhAfterFactoryBalanceService zsyhAfterFactoryBalanceService;

    @Autowired
    private IZsyhAfterFactoryMenuService zsyhAfterFactoryMenuService;

    @Autowired
    private IZsyhServiceOrderService zsyhServiceOrderService;

    /**
     * 厂家 登陆
     * @return
     */
    @RequestMapping("/factoryLogin")
    @ResponseBody
    public AjaxResult factoryLogin(String account, String password)throws Exception
    {
        ZsyhAfterFactoryLogin factoryLogin = zsyhAfterFactoryLoginService.selectZsyhAfterFactoryLoginByAccount(account);
        if(factoryLogin != null){
            password = new Md5Hash(password).toHex();
            if(password.equals(factoryLogin.getLoginPassword())){
                ZsyhAfterFactory factory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(factoryLogin.getFactoryId());
                Map map = new HashMap();
                map.put("factoryName", factory.getFactoryName());
                map.put("factoryLogin", factoryLogin);
                return success("登陆成功", map);
            }else{
                return error("登陆失败，密码错误");
            }
        }
        return error("登陆失败，账号不存在");

    }

    /**
     * 获取厂家菜单
     * @param loginId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFactoryMenu")
    @ResponseBody
    public AjaxResult getFactoryMenu(String loginId)throws Exception
    {
        ZsyhAfterFactoryLogin factoryLogin = zsyhAfterFactoryLoginService.selectZsyhAfterFactoryLoginById(loginId);
        if(factoryLogin != null){
            ZsyhAfterFactoryMenu menu = new ZsyhAfterFactoryMenu();
            menu.setMenuParentid("0");
            List<ZsyhAfterFactoryMenu> menuList = zsyhAfterFactoryMenuService.selectZsyhAfterFactoryMenuList(menu);
            Map map = new HashMap<>();
            map.put("loginType", factoryLogin.getLoginType());
            for(ZsyhAfterFactoryMenu a:menuList){
                menu = new ZsyhAfterFactoryMenu();
                menu.setMenuParentid(a.getId());
                menu.setParams(map);
                List<ZsyhAfterFactoryMenu> zMenuList = zsyhAfterFactoryMenuService.selectZsyhAfterFactoryMenuList(menu);
                a.setMenuList(zMenuList);
            }

            return success("成功", menuList);

        }
        return error("账号不存在");

    }

    /**
     * 修改密码
     * @param loginId
     * @param passwordOld
     * @param password
     * @return
     * @throws Exception
     */
    @RequestMapping("/updateLoginPassword")
    @ResponseBody
    public AjaxResult updateLoginPassword(String loginId, String passwordOld, String password)throws Exception
    {
        ZsyhAfterFactoryLogin factoryLogin = zsyhAfterFactoryLoginService.selectZsyhAfterFactoryLoginById(loginId);
        if(factoryLogin != null){
            passwordOld = new Md5Hash(passwordOld).toHex();
            if(passwordOld.equals(factoryLogin.getLoginPassword())){
                factoryLogin = new ZsyhAfterFactoryLogin();
                factoryLogin.setId(loginId);
                factoryLogin.setLoginPassword(new Md5Hash(password).toHex());
                zsyhAfterFactoryLoginService.updateZsyhAfterFactoryLogin(factoryLogin);
                return success("修改成功");
            }else{
                return error("修改失败，旧密码错误");
            }
        }
        return error("失败，账号不存在");

    }

    /**
     * 获取厂家信息
     * @param factoryId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFactoryById")
    @ResponseBody
    public AjaxResult getFactoryById(String factoryId)throws Exception
    {
        ZsyhAfterFactory factory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(factoryId);
        return success("成功", factory);
    }


    /**
     * 修改厂家信息
     * @throws Exception
     */
    @RequestMapping("/updateFactoryInformation")
    @ResponseBody
    public AjaxResult updateFactoryInformation(String factoryId, String factoryPerson, String factoryPhone, String factoryProvinceName, String factoryProvice,
            String factoryCityName, String factoryCity, String factoryDistrictName, String factoryDistrict, String factoryAddress, String isSelfParts)throws Exception
    {
        ZsyhAfterFactory factory = new ZsyhAfterFactory();
        factory.setId(factoryId);
        factory.setFactoryPerson(factoryPerson);
        factory.setFactoryPhone(factoryPhone);
        factory.setFactoryProvinceName(factoryProvinceName);
        factory.setFactoryProvice(factoryProvice);
        factory.setFactoryCityName(factoryCityName);
        factory.setFactoryCity(factoryCity);
        factory.setFactoryDistrictName(factoryDistrictName);
        factory.setFactoryDistrict(factoryDistrict);
        factory.setFactoryAddress(factoryAddress);
//        factory.setIsSelfParts(isSelfParts);//是否使用自购件 1是 0否
        zsyhAfterFactoryService.updateZsyhAfterFactory(factory);

        return success("操作成功");

    }


    /**
     * 厂家 获取所有账户列表
     * @return
     */
    @RequestMapping("/getFactoryLoginList")
    @ResponseBody
    public AjaxResult getFactoryLoginList(String factoryId, String loginName, String loginPhone, String pageNum, String pageSize)throws Exception
    {
        ZsyhAfterFactoryLogin login = new ZsyhAfterFactoryLogin();
        login.setFactoryId(factoryId);
        login.setLoginName(loginName);
        login.setLoginPhone(loginPhone);
        List<ZsyhAfterFactoryLogin> listSize = zsyhAfterFactoryLoginService.selectZsyhAfterFactoryLoginList(login);
        int total = listSize.size();
        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        login.setParams(map);
        List<ZsyhAfterFactoryLogin> list = zsyhAfterFactoryLoginService.selectZsyhAfterFactoryLoginList(login);

        return success("成功", list, total);
    }

    /**
     * 厂家 添加子账号
     * @return
     */
    @RequestMapping("/saveFactoryLogin")
    @ResponseBody
    public AjaxResult saveFactoryLogin(String factoryId, String loginName, String loginPhone, String loginAccount, String loginPassword)throws Exception
    {
        ZsyhAfterFactoryLogin login = new ZsyhAfterFactoryLogin();
        login.setFactoryId(factoryId);
        login.setId(IdWorker.getId());
        login.setLoginName(loginName);
        login.setLoginPhone(loginPhone);
        login.setLoginAccount(loginAccount);
        login.setLoginPassword(new Md5Hash(loginPassword).toHex());
        login.setLoginType("2");
        zsyhAfterFactoryLoginService.insertZsyhAfterFactoryLogin(login);
        return success("操作成功");
    }

    /**
     * 厂家 修改子账号
     * @return
     */
    @RequestMapping("/updateFactoryLogin")
    @ResponseBody
    public AjaxResult updateFactoryLogin(String id, String loginName, String loginPhone, String loginAccount, String loginPassword, String loginValid)throws Exception
    {
        ZsyhAfterFactoryLogin login1 = zsyhAfterFactoryLoginService.selectZsyhAfterFactoryLoginById(id);


        ZsyhAfterFactoryLogin login = new ZsyhAfterFactoryLogin();
        login.setId(id);
        login.setLoginName(loginName);
        login.setLoginPhone(loginPhone);
        login.setLoginAccount(loginAccount);
        if(!login1.getLoginPassword().equals(loginPassword)){
            login.setLoginPassword(new Md5Hash(loginPassword).toHex());
        }
        login.setLoginType("2");
        login.setLoginValid(loginValid);
        zsyhAfterFactoryLoginService.updateZsyhAfterFactoryLogin(login);
        return success("操作成功");
    }


    /**
     * 获取厂家余额信息
     * @param factoryId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFactoryMoneyById")
    @ResponseBody
    public AjaxResult getFactoryMoneyById(String factoryId)throws Exception
    {
        ZsyhAfterFactory factory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(factoryId);

        //orderState 订单状态 0未接单（厂家下单）1已接单 101已预约 102服务中 2已完成 201平台待审核 202厂家待审核 203待拨款 3已支付 4已评价 5已取消 501师傅申请取消 6系统自动取消
        Map orderList1 = zsyhServiceOrderService.getMoneyAllList(null, factoryId, "203");//待结算工单金额
        Map orderList2 = zsyhServiceOrderService.getMoneyAllList(null, factoryId, "3");//已结算工单金额

        Map map = new HashedMap();
        map.put("moneyAllNot", orderList1.get("moneyAllRepair"));
        map.put("moneyAll", orderList2.get("moneyAllRepair"));
        map.put("factoryAll", factory.getFactoryAll());
        map.put("factoryBalance", factory.getFactoryBalance());
        map.put("factoryFreeze", factory.getFactoryFreeze());
        map.put("factoryMoney", factory.getFactoryMoney());
        map.put("factoryName", factory.getFactoryName());

        return success("成功", map);
    }


    /**
     * 获取所有登陆人
     * @param factoryId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFactoryLoginAll")
    @ResponseBody
    public AjaxResult getFactoryLoginAll(String factoryId)throws Exception
    {
        ZsyhAfterFactoryLogin login = new ZsyhAfterFactoryLogin();
        login.setFactoryId(factoryId);
        List<ZsyhAfterFactoryLogin> list = zsyhAfterFactoryLoginService.selectZsyhAfterFactoryLoginList(login);
        return success("成功", list);
    }

    /**
     * 获取厂家充值记录
     * @param factoryId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFactoryBalanceDetails")
    @ResponseBody
    public AjaxResult getFactoryBalanceDetails(String pageNum, String pageSize,
                                               String factoryId, String balancePayType, String startDate, String endDate, String factoryLoginId)throws Exception
    {

        ZsyhAfterFactoryBalance balance = new ZsyhAfterFactoryBalance();
        balance.setFactoryId(factoryId);
        balance.setBalancePayType(balancePayType);
        balance.setFactoryLoginId(factoryLoginId);
        balance.setBalanceRechargeState("1");

        Map map = new HashedMap();
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("充值", "1");
        balance.setParams(map);
        List<ZsyhAfterFactoryBalance> listSize = zsyhAfterFactoryBalanceService.selectZsyhAfterFactoryBalanceList(balance);

        int total = listSize.size();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        balance.setParams(map);
        List<ZsyhAfterFactoryBalance> list = zsyhAfterFactoryBalanceService.selectZsyhAfterFactoryBalanceList(balance);

        return success("成功", list, total);
    }

    public static void main(String args[]){
        String appId = "wxf7cad0b2743a6eaf";
        String appSecretWx = "481b3c0704cdd135c1ea4f0987487d2f";
        String partnerKey = "dfte9809FWEJL239E4830FWKFCD3DE89";
        String mchid = "1528613081";
        String description = "余额充值";
        String out_trade_no = IdWorker.getId();
        String notify_url = "https://www.baidu.com";
        int total = 1;
        Map amount = new HashMap();
        amount.put("total", total);

        Map data = new HashMap();
        data.put("appId", appId);
        data.put("mchid", mchid);
        data.put("description", description);
        data.put("out_trade_no", out_trade_no);
        data.put("notify_url", notify_url);
        data.put("amount", amount);



        // 订单生成的机器 IP
        String trade_type = "NATIVE";

        // ---必须参数
        // 商户号
        String mch_id = mchid;
        // 随机字符串
        String nonce_str = StringUtils.getNonceStr();

        // 商品描述根据情况修改
        String body = description;

        // 商户订单号

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appId);
        packageParams.put("attach", "attach");
        packageParams.put("body", body);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);

        packageParams.put("notify_url", notify_url);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("spbill_create_ip", "127.0.0.1");
        packageParams.put("total_fee", "1");
        packageParams.put("trade_type", trade_type);


        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appId, appSecretWx, partnerKey);

        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>" + "<appid>" + appId + "</appid>" + "<mch_id>"
                + mch_id + "</mch_id>" + "<nonce_str>" + nonce_str
                + "</nonce_str>" + "<sign>" + sign + "</sign>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<out_trade_no>" + out_trade_no
                + "</out_trade_no>" + "<attach>" + "attach" + "</attach>"
                + "<total_fee>" + "1" + "</total_fee>"
                + "<spbill_create_ip>" + "127.0.0.1"
                + "</spbill_create_ip>" + "<notify_url>" + notify_url
                + "</notify_url>" + "<trade_type>" + trade_type
                + "</trade_type>"
                + "</xml>";
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";


        Map map = new GetWxOrderno().getPayNoMap(createOrderURL, xml);

        System.out.println(JSONObject.toJSON(map));


    }
}
